//#include "mainwindow.h"
#include <QApplication>
#include "freetype2.h"
#include "Glyph.h"
#include "AbstractDrawer.h"
#include <QWidget>
#include <QPainter>
#include <QDebug>
using namespace FT;
ulong text[12] = {0x041A,0x0440,0x0443,0x0442,0x043E,0x0439,0x0020,

                         0x0442,0x0435,0x043A,0x0441, 0x0442};

class MyWidget : public QWidget
{
public:
    MyWidget();

protected:
    void paintEvent(QPaintEvent *);
    FontFace* ff;
};

class QGlyph : public FT::BaseGlyph
{
public:
    QGlyph(uint index, Point advance, Point horisontalBearing, FontFace &face, GlyphGenericBitmap &genericBitmap)
        :BaseGlyph(index,advance,horisontalBearing,face,genericBitmap)
    {
        imgData = new uchar[genericBitmap.pitch * genericBitmap.rows];
        for (int i = 0; i < genericBitmap.pitch * genericBitmap.rows; ++i) {
            imgData[i] = genericBitmap.buffer[i];
        }
        img = new QImage(imgData, genericBitmap.width, genericBitmap.rows, genericBitmap.pitch, QImage::Format_Indexed8);
        QVector<QRgb> colorTable;
        for (int i = 0; i < 256; ++i)
        {
            colorTable << qRgba(0, 0, 0, i);
        }
        img->setColorTable(colorTable);
    }
    virtual ~QGlyph()
    {
        delete imgData;
        delete img;
    }
    QImage &getImage()
    {
        return *img;
    }
private:
    uchar* imgData;
    QImage* img;
};

class QDrawer : public FT::AbstractDrawer<QGlyph>
{
public:
    QDrawer(FT::FontFace &face, QPainter &painter):AbstractDrawer(face),painter(painter)
    {}

protected:
    virtual void drawGlyph(QGlyph *glyph, int x, int y)
    {
        QGlyph* _glyph = (QGlyph*)glyph;
        painter.drawImage(x,y,_glyph->getImage());
    }
private:
    QPainter &painter;
};

MyWidget::MyWidget()
{
    try{
        FreeType2::InitLibrary();
        ff = new FontFace("C:\\times.TTF");
        ff->setCharSize(8);
    }
    catch (ft2exception e)
    {
        qDebug() << QString(e.what().c_str());
    }
}

void MyWidget::paintEvent(QPaintEvent *)
{
    try{
        QPainter painter(this);
        QDrawer drawer(*ff,painter);
        ff->setCharSize(5);
        drawer.setText(text,12);
        drawer.draw(100,100);
        ff->setCharSize(5);
        drawer.setText(text,12);
        drawer.draw(100,200);
    }
    catch (ft2exception e)
    {
        qDebug() << QString(e.what().c_str());
    }

}
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    //MainWindow w;
    //w.show();
    MyWidget w;
    w.show();
    
    return a.exec();
}
